import type { EmailOtpType } from '@liam-hq/db'
import { redirect } from 'next/navigation'
import type { NextRequest } from 'next/server'
import { sanitizeReturnPath } from '../../components/LoginPage/services/validateReturnPath'
import { createClient } from '../../libs/db/server'
import { urlgen } from '../../libs/routes/urlgen'

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const token_hash = searchParams.get('token_hash')
  const type = searchParams.get('type') as EmailOtpType | null
  const next = sanitizeReturnPath(searchParams.get('next'), '/')

  if (token_hash && type) {
    const supabase = await createClient()

    const { error } = await supabase.auth.verifyOtp({
      type,
      token_hash,
    })
    if (!error) {
      // redirect user to specified redirect URL or root of app
      redirect(next)
    }
    console.error('Email confirmation OTP verification failed:', {
      error: error.message,
      type,
      timestamp: new Date().toISOString(),
    })
  } else {
    console.error('Email confirmation missing parameters:', {
      hasToken: !!token_hash,
      hasType: !!type,
      timestamp: new Date().toISOString(),
    })
  }

  // redirect the user to an error page with some instructions
  redirect(urlgen('error'))
}
